using Microsoft.EntityFrameworkCore;
using MediPlatform.Domain.Order;
using MediPlatform.Infeartructure;
using MediPlatform.Read.Api.Models;
using MediPlatform.ErrorCode;

namespace MediPlatform.Read.Api.Services
{
    public class MedicalOrderService
    {
        private readonly MyDbContext _context;
        private readonly ILogger<MedicalOrderService> _logger;

        public MedicalOrderService(MyDbContext context, ILogger<MedicalOrderService> logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task<MedicalOrderPagedResponse> GetPagedListAsync(MedicalOrderQueryRequest request)
        {
            try
            {
                _logger.LogInformation("开始查询药品订单列表，参数：{@Request}", request);

                // 检查数据库连接
                if (!_context.Database.CanConnect())
                {
                    _logger.LogError("无法连接到数据库");
                    throw new InvalidOperationException("数据库连接失败");
                }

                var query = _context.MedicalOrder
                    .Include(mo => mo.User)
                    .AsQueryable();

                // 应用筛选条件
                if (!string.IsNullOrWhiteSpace(request.OrderNoOrUsername))
                {
                    var searchTerm = request.OrderNoOrUsername.Trim();
                    query = query.Where(mo => 
                        (mo.OrderNo != null && mo.OrderNo.Contains(searchTerm)) ||
                        (mo.User != null && mo.User.PhoneNumber != null && mo.User.PhoneNumber.Contains(searchTerm))
                    );
                }

                if (request.StartTime.HasValue)
                {
                    query = query.Where(mo => mo.CreatedAt >= request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    var endTime = request.EndTime.Value.AddDays(1).AddSeconds(-1);
                    query = query.Where(mo => mo.CreatedAt <= endTime);
                }

                if (request.Status.HasValue)
                {
                    query = query.Where(mo => mo.Status == request.Status.Value);
                }

                var totalCount = await query.CountAsync();

                var items = await query
                    .OrderByDescending(mo => mo.CreatedAt)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .Select(mo => new MedicalOrderListItem
                    {
                        Id = mo.Id,
                        OrderNo = mo.OrderNo,
                        CreatedAt = mo.CreatedAt,
                        Username = mo.User != null ? mo.User.PhoneNumber : null,
                        Recipient = ExtractRecipientFromAddress(mo.DeliveryAddress),
                        TotalAmount = mo.TotalAmount,
                        Status = mo.Status,
                        StatusText = GetStatusText(mo.Status),
                        LogisticsCompany = mo.LogisticsCompany,
                        TrackingNumber = mo.TrackingNumber
                    })
                    .ToListAsync();

                var result = new MedicalOrderPagedResponse
                {
                    Items = items,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling((double)totalCount / request.PageSize),
                    CurrentPage = request.PageIndex,
                    PageSize = request.PageSize
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取药品订单分页列表失败");
                throw;
            }
        }

        public async Task<MedicalOrderDetailResponse?> GetDetailAsync(long id)
        {
            try
            {
                var order = await _context.MedicalOrder
                    .Include(mo => mo.User)
                    .FirstOrDefaultAsync(mo => mo.Id == id);

                if (order == null) return null;

                var orderItems = await _context.MedicalOrderItem
                    .Where(oi => oi.OrderId == id)
                    .Select(oi => new MedicalOrderItemInfo
                    {
                        Id = oi.Id,
                        MedicineId = oi.MedicineId,
                        MedicineName = oi.MedicineName,
                        Specification = oi.Specification,
                        UnitPrice = oi.UnitPrice,
                        Quantity = oi.Quantity,
                        Subtotal = oi.Subtotal
                    })
                    .ToListAsync();

                var logisticsTracking = await _context.MedicalOrderLogisticsTracking
                    .Where(lt => lt.OrderId == id)
                    .OrderByDescending(lt => lt.UpdateTime)
                    .Select(lt => new LogisticsTrackingInfo
                    {
                        Id = lt.Id,
                        TrackingNumber = lt.TrackingNumber,
                        LogisticsCompany = lt.LogisticsCompany,
                        Location = lt.Location,
                        Status = lt.Status,
                        StatusText = GetLogisticsStatusText(lt.Status),
                        UpdateTime = lt.UpdateTime,
                        ExtraInfo = lt.ExtraInfo
                    })
                    .ToListAsync();

                var result = new MedicalOrderDetailResponse
                {
                    OrderInfo = new MedicalOrderInfo
                    {
                        Id = order.Id,
                        OrderNo = order.OrderNo,
                        UserId = order.UserId,
                        Username = order.User?.PhoneNumber,
                        TotalAmount = order.TotalAmount,
                        ActualAmount = order.ActualAmount,
                        Status = order.Status,
                        StatusText = GetStatusText(order.Status),
                        PaymentMethod = order.PaymentMethod,
                        PaymentTime = order.PaymentTime,
                        DeliveryAddress = order.DeliveryAddress,
                        LogisticsCompany = order.LogisticsCompany,
                        TrackingNumber = order.TrackingNumber,
                        SignTime = order.SignTime,
                        CreatedAt = order.CreatedAt,
                        UpdatedAt = order.UpdatedAt
                    },
                    OrderItems = orderItems,
                    LogisticsTracking = logisticsTracking
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取药品订单详情失败，ID：{Id}", id);
                throw;
            }
        }

        public async Task<MedicalOrderStatisticsResponse> GetStatisticsAsync()
        {
            try
            {
                var totalCount = await _context.MedicalOrder.CountAsync();
                // 待发货：状态为0的订单
                var pendingShipmentCount = await _context.MedicalOrder.CountAsync(mo => mo.Status == 0);
                // 待收货：状态为1的订单
                var pendingReceiptCount = await _context.MedicalOrder.CountAsync(mo => mo.Status == 1);
                // 已收货：状态为2的订单
                var receivedCount = await _context.MedicalOrder.CountAsync(mo => mo.Status == 2);
                // 已取消：状态为6的订单（保留取消状态）
                var cancelledCount = await _context.MedicalOrder.CountAsync(mo => mo.Status == 6);

                var result = new MedicalOrderStatisticsResponse
                {
                    TotalCount = totalCount,
                    PendingShipmentCount = pendingShipmentCount,
                    PendingReceiptCount = pendingReceiptCount,
                    ReceivedCount = receivedCount,
                    CancelledCount = cancelledCount
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取药品订单统计信息失败");
                throw;
            }
        }

        /// <summary>
        /// 订单发货
        /// </summary>
        public async Task<bool> ShipOrderAsync(long orderId, string logisticsCompany, string trackingNumber)
        {
            try
            {
                var order = await _context.MedicalOrder.FindAsync(orderId);
                if (order == null)
                {
                    _logger.LogWarning("订单不存在，ID：{OrderId}", orderId);
                    return false;
                }

                if (order.Status != 0) // 只有待发货状态的订单才能发货
                {
                    _logger.LogWarning("订单状态不正确，无法发货，订单ID：{OrderId}，当前状态：{Status}", orderId, order.Status);
                    return false;
                }

                // 更新订单状态为待收货
                order.Status = 1;
                order.LogisticsCompany = GetLogisticsCompanyName(logisticsCompany);
                order.TrackingNumber = trackingNumber;
                order.UpdatedAt = DateTime.Now;

                // 添加物流追踪记录
                var logisticsTracking = new MedicalOrderLogisticsTracking
                {
                    OrderId = orderId,
                    TrackingNumber = trackingNumber,
                    LogisticsCompany = GetLogisticsCompanyName(logisticsCompany),
                    Location = "北京市朝阳区仓库",
                    Status = 1, // 待收货
                    UpdateTime = DateTime.Now,
                    ExtraInfo = "包裹已发出，正在配送中"
                };

                _context.MedicalOrderLogisticsTracking.Add(logisticsTracking);
                await _context.SaveChangesAsync();

                _logger.LogInformation("订单发货成功，订单ID：{OrderId}，物流公司：{LogisticsCompany}，物流单号：{TrackingNumber}", 
                    orderId, logisticsCompany, trackingNumber);

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "订单发货失败，订单ID：{OrderId}", orderId);
                throw;
            }
        }

        /// <summary>
        /// 确认收货
        /// </summary>
        public async Task<bool> ConfirmReceiptAsync(long orderId)
        {
            try
            {
                var order = await _context.MedicalOrder.FindAsync(orderId);
                if (order == null)
                {
                    _logger.LogWarning("订单不存在，ID：{OrderId}", orderId);
                    return false;
                }

                if (order.Status != 1) // 只有待收货状态的订单才能确认收货
                {
                    _logger.LogWarning("订单状态不正确，无法确认收货，订单ID：{OrderId}，当前状态：{Status}", orderId, order.Status);
                    return false;
                }

                // 更新订单状态为已收货
                order.Status = 2;
                order.SignTime = DateTime.Now;
                order.UpdatedAt = DateTime.Now;

                // 添加物流追踪记录
                var logisticsTracking = new MedicalOrderLogisticsTracking
                {
                    OrderId = orderId,
                    TrackingNumber = order.TrackingNumber,
                    LogisticsCompany = order.LogisticsCompany,
                    Location = "北京市朝阳区收货地址",
                    Status = 2, // 已收货
                    UpdateTime = DateTime.Now,
                    ExtraInfo = "包裹已送达，请及时签收"
                };

                _context.MedicalOrderLogisticsTracking.Add(logisticsTracking);
                await _context.SaveChangesAsync();

                _logger.LogInformation("确认收货成功，订单ID：{OrderId}", orderId);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "确认收货失败，订单ID：{OrderId}", orderId);
                throw;
            }
        }

        /// <summary>
        /// 获取物流公司列表
        /// </summary>
        public List<LogisticsCompanyInfo> GetLogisticsCompanies()
        {
            return new List<LogisticsCompanyInfo>
            {
                new() { Code = "SF", Name = "顺丰快递" },
                new() { Code = "JD", Name = "京东物流" },
                new() { Code = "DB", Name = "德邦快递" },
                new() { Code = "YT", Name = "圆通快递" },
                new() { Code = "ST", Name = "申通快递" },
                new() { Code = "ZT", Name = "中通快递" },
                new() { Code = "YD", Name = "韵达快递" },
                new() { Code = "EMS", Name = "EMS" }
            };
        }

        /// <summary>
        /// 获取物流追踪详情（模拟数据）
        /// </summary>
        public LogisticsTrackingDetailResponse GetLogisticsTrackingDetail(long orderId)
        {
            var order = _context.MedicalOrder.Find(orderId);
            if (order == null)
            {
                return new LogisticsTrackingDetailResponse();
            }

            // 生成模拟的物流追踪数据
            var trackingRecords = new List<LogisticsTrackingRecord>
            {
                new()
                {
                    Time = DateTime.Now.AddDays(-3),
                    Status = "订单开始处理",
                    Location = "北京市朝阳区仓库"
                },
                new()
                {
                    Time = DateTime.Now.AddDays(-3).AddHours(2),
                    Status = "已发货 卖家已发货",
                    Location = "北京市朝阳区仓库"
                },
                new()
                {
                    Time = DateTime.Now.AddDays(-2),
                    Status = "已揽件 包裹正在揽收",
                    Location = "北京市朝阳区配送中心"
                },
                new()
                {
                    Time = DateTime.Now.AddDays(-1),
                    Status = "快件在【华北陆运枢纽(天津)】已装车; 准备发往【北京顺义集散中心】",
                    Location = "华北陆运枢纽(天津)"
                },
                new()
                {
                    Time = DateTime.Now.AddDays(-1).AddHours(6),
                    Status = "快件到达【北京顺义集散中心】",
                    Location = "北京顺义集散中心"
                },
                new()
                {
                    Time = DateTime.Now.AddHours(-2),
                    Status = "快件到达【北京朝阳区营业部】",
                    Location = "北京朝阳区营业部"
                },
                new()
                {
                    Time = DateTime.Now.AddMinutes(-30),
                    Status = "快件正在派送",
                    Location = "北京市朝阳区"
                }
            };

            return new LogisticsTrackingDetailResponse
            {
                OrderNo = order.OrderNo ?? "",
                LogisticsCompany = order.LogisticsCompany ?? "",
                TrackingNumber = order.TrackingNumber ?? "",
                TrackingRecords = trackingRecords
            };
        }

        private static string? ExtractRecipientFromAddress(string? deliveryAddress)
        {
            if (string.IsNullOrWhiteSpace(deliveryAddress)) return null;

            try
            {
                var parts = deliveryAddress.Split(',');
                if (parts.Length > 0) return parts[0].Trim();
            }
            catch { }

            return deliveryAddress;
        }

        private static string GetStatusText(int? status)
        {
            return status switch
            {
                0 => "待发货",
                1 => "待收货",
                2 => "已收货",
                _ => "未知状态"
            };
        }

        private static string GetLogisticsStatusText(int? status)
        {
            return status switch
            {
                0 => "待发货",
                1 => "待收货",
                2 => "已收货",
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 根据物流公司代码获取名称
        /// </summary>
        private static string GetLogisticsCompanyName(string code)
        {
            return code switch
            {
                "SF" => "顺丰快递",
                "JD" => "京东物流",
                "DB" => "德邦快递",
                "YT" => "圆通快递",
                "ST" => "申通快递",
                "ZT" => "中通快递",
                "YD" => "韵达快递",
                "EMS" => "EMS",
                _ => code
            };
        }

        /// <summary>
        /// 获取数据库上下文（用于测试）
        /// </summary>
        public MyDbContext GetDbContext()
        {
            return _context;
        }
    }
} 